﻿using MySqlConnector;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Text.Json;
using Traceability.Commont.Domains.BatchManagementFiles;

namespace Butcher.winform.EnterpriseForms.MessSalguhterPut
{
    public partial class MassSlaughterSearch : Form
    {
        public MassSlaughterSearch()
        {
            InitializeComponent();
            string url = @"http://localhost:5229/api/Batch/BulkSlaughterSearch";
            HttpClient client = new HttpClient();
            BulkSlaughter ctr = new BulkSlaughter();
            var sh = 0;
            var content = new StringContent(JsonSerializer.Serialize<BulkSlaughter>(ctr));
            content.Headers.Remove("Content-Type");
            content.Headers.Add("Content-Type", "application/json");
            string result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
            JObject info = JObject.Parse(result);
            var saaa = result;
            var aaa = info["date"].Value<JArray>();
            List<BulkSlaughter> cts = aaa.ToObject<List<BulkSlaughter>>();
            var c = 1;
            foreach (var ct in cts)
            {
                uiDataGridView1.DataSource = cts;
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFile.FileName;
                DataTable excelDt = ExcelHelper.ReadFromExcel(filePath);
                //把Excel读取到DataTable里面 然后再把DataTable存入数据库
                AddDataTableToDB(excelDt);
            }
        }
        public bool AddDataTableToDB(DataTable source)
        {
            MySqlTransaction tran = null;//声明一个事务对象
            try
            {
                using (MySqlConnection conn = new MySqlConnection("server=112.124.69.237;port=3306;uid=root;pwd=No6123666;database=SlaughterDB;AllowLoadLocalInfile=true"))
                {
                    conn.Open();//打开链接
                    using (tran = conn.BeginTransaction())
                    {
                        MySqlBulkCopy copy = new MySqlBulkCopy(conn, tran);
                        // using ()
                        copy.DestinationTableName = "bulkslaughters";  //指定服务器上目标表的名称
                        copy.WriteToServer(source);  //执行把DataTable中的数据写入DB  注意DataTable表结构要与数据库表结构一样
                        tran.Commit();              //提交事务
                        return true;               //返回True 执行成功！
                    }
                }
            }
            catch (Exception ex)
            {
                if (null != tran)
                    tran.Rollback();
                //LogHelper.Add(ex);
                return false;//返回False 执行失败！
            }
        }
    }
}
